package wxapi

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gitee.com/xmcommon/mlog"
	"net/http"
	"time"
)

type reqSendBody struct {
	AccessToken string                 `json:"access_token"`
	Touser      string                 `json:"touser"`
	TemplateId  string                 `json:"template_id"`
	Page        string                 `json:"page"`
	FormId      string                 `json:"form_id"`
	Data        map[string]interface{} `json:"data"`
}

func PushMsg(accessToken, openId, formId, content, jumpPage string) (expires bool, err error) {
	currentTime := time.Now().Format("2006-01-02 15:04:05")
	data := make(map[string]interface{})
	keyword1 := make(map[string]interface{})
	keyword1["value"] = content
	data["keyword1"] = keyword1
	keyword2 := make(map[string]interface{})
	keyword2["value"] = currentTime
	data["keyword2"] = keyword2

	url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s", accessToken)

	req := reqSendBody{
		Touser:     openId, //openid
		TemplateId: "QfTn9IJrIeyFJtE8lY7Co7v1Ywio-JLm2GqLaPQGDEk",
		Page:       jumpPage,
		FormId:     formId, //
		Data:       data,
	}
	params, err := json.Marshal(req)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	request, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(params))
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	res, err := commonPost(request)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	var r respCheckMsg
	err = json.Unmarshal(res, &r)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	if r.Errcode == 40001 {
		return true, nil
	} else if r.Errcode != 0 {
		err = fmt.Errorf(r.Errmsg)
		mlog.Log.Error(err.Error())
		return
	}
	return
}
